﻿using System; 
using System.Web.UI;
using System.Text;
using System.IO;
using System.Globalization;

using SiteUnity.Layers.Application.Rates;
using SiteUnity.Layers.Application;
using SiteUnity.Layers.Application.BaseClasses; 

namespace SiteUnity.Frame.Modules
{
    [ToolboxData("<{0}:StarRate runat=server />")]
    public class StarRate : BaseWebControl
    {
        public StarRate()
        {
            if (Size==default(int))
                Size = 5;

            if (string.IsNullOrEmpty(AjaxRatePage))
                AjaxRatePage = SiteManager.FindWebsiteSettingByKey("StarRate-AjaxPage").Value;

            if (CurrentPage == null)
                CurrentPage = SiteManager.Website.CurrentPage;
        }

        public int Size { get; set; }
        public string AjaxRatePage { get; set; }
        public SiteUnity.Layers.Entity.General.Page CurrentPage { get; set; }

        private void generateStarRate(HtmlTextWriter output)
        {
            output.AddAttribute(HtmlTextWriterAttribute.Id, CurrentPage.Guid.ToString());
            output.AddAttribute(HtmlTextWriterAttribute.Class, "Grid star-container");
            output.RenderBeginTag(HtmlTextWriterTag.Ul);

            for (int i = 0; i < Size; i++)
            {
                output.AddAttribute(HtmlTextWriterAttribute.Class, "star-item");
                output.RenderBeginTag(HtmlTextWriterTag.Li);
                output.RenderEndTag();
            }

            output.RenderEndTag();
        }

        protected override void OnPreRender(EventArgs e)
        {
            string starready = @"$(function () {
                                    $('#{3}').StarRating({ imageUrl: '{0}', currentRate: {2}, ajaxRatePage: '{1}', currentPage: '{3}' });
                                });";

            decimal currentValue =  RateManager.getRateAvarageByPage(CurrentPage);

            if (currentValue==-1)
                currentValue = Size/2;
            
            starready = starready.Replace("{0}",Page.ClientScript.GetWebResourceUrl(this.GetType(), "SiteUnity.Frame.Modules.Rating.StarRating.star.png"))
                                    .Replace("{1}",AjaxRatePage)
                                    .Replace("{2}",currentValue.ToString())
                                    .Replace("{3}", CurrentPage.Guid.ToString());

            Page.ClientScript.RegisterStartupScript(typeof(Page), this.ClientID, starready, true);
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb, CultureInfo.InvariantCulture));

            generateStarRate(output);

            output.Write(sb.ToString());
        }

    }
}